//app.js
const App = require('./utils/ald-stat.js').App;
App({
  onLaunch: function() {
    let that = this;
    //调取微信登陆接口
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let code = res.code;
        if (res.code) {
          that.apiRequest('wx/login/', 'POST', {
            code: code
          }, res => {
            if (res.result.avatar_url != null) {
              wx.setStorageSync('userIcon', res.result.avatar_url);
              wx.setStorageSync('nick_name', res.result.nick_name);
            }
            wx.setStorageSync('token', res.result.token);
          }, error => {
            return ''
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
  },
  onShow() {

  },
  // //需要授权的请求接口
  authApiRequest: function(url, method, params, success, failure) {
    wx.request({
      url: this.globalData.config.HTTP_BASE_URL + url,
      method: method,
      data: params,
      header: {
        'content-type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
        'Authorization': 'JWT' + ' ' + wx.getStorageSync('token')
      },
      success: res => {
        if (res.data.code == 1) {
          success(res.data)
        } else {
          if (failure) {
            failure(res)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: res.data.error_msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      }
    })
  },
  //不需要授权的请求接口

  apiRequest: function(url, method, params, success, failure) {
    wx.request({
      url: this.globalData.config.HTTP_BASE_URL + url,
      method: method,
      data: params,
      header: {
        'content-type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
      },
      success: res => {
        if (res.data.code == 1) {
          success(res.data)
        } else {
          if (failure) {
            failure(res)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: res.data.error_msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      }
    })
  },
  globalData: {
    userInfo: {},
    token: '',
    config: {
      // socket_url: 'wss://://wss.xinnongtang.cn',
      HTTP_BASE_URL: 'https://cicadas.zhiliaowo.net/api/',
      // APPID: '1',
      // token: '11111111111111111111111111111111',
      // PHPSESSID: ''
    },
  }
})